import { getDB } from '../db/connection.js';

class UserUpdate {
  static async getAll() {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM user_updates');
    return rows;
  }

  static async getById(id) {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM user_updates WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByUserId(userId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_updates WHERE user_id = ?',
      [userId]
    );
    return rows;
  }

  static async getByComponentVersionId(componentVersionId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_updates WHERE component_version_id = ?',
      [componentVersionId]
    );
    return rows;
  }

  static async getByUserIdAndComponentVersionId(userId, componentVersionId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_updates WHERE user_id = ? AND component_version_id = ?',
      [userId, componentVersionId]
    );
    return rows.length > 0 ? rows[0] : null;
  }

  static async recordUpdate(userId, componentVersionId) {
    const db = await getDB();
    // 检查用户是否已经更新过该版本
    const existingUpdate = await this.getByUserIdAndComponentVersionId(userId, componentVersionId);
    
    if (!existingUpdate) {
      const [result] = await db.execute(
        'INSERT INTO user_updates (user_id, component_version_id) VALUES (?, ?)',
        [userId, componentVersionId]
      );
      return this.getById(result.insertId);
    }
    
    return existingUpdate;
  }

  static async delete(id) {
    const db = await getDB();
    await db.execute('DELETE FROM user_updates WHERE id = ?', [id]);
  }

  static async deleteByUserIdAndComponentVersionId(userId, componentVersionId) {
    const db = await getDB();
    await db.execute(
      'DELETE FROM user_updates WHERE user_id = ? AND component_version_id = ?',
      [userId, componentVersionId]
    );
  }
}

export default UserUpdate;
